Vue.component("yl-upload", {
  template: `<div>
    <div class="preview" v-if="Picture_URL">
        <el-image ref="FImage" class="el-upload-list__item-thumbnail" style="width: 148px; height: 148px" :preview-src-list="[base64?Picture_URL:base + Picture_URL]" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions">
            <span @click="handlePictureCardPreview('FImage')"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
  props: {
    value: {
      type: String,
      default: "",
    },
    base: {
      type: String,
      default: "",
    },
    base64: {
      type: Boolean,
      default: false,
    },
    unslider: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      Picture_URL: this.value,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      quality: 100,
    };
  },
  watch: {
    value(newVal) {
      this.Picture_URL = newVal;
    },
    Picture_URL(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    formatTooltip(val) {
      return "图片压缩比例：" + val + "%";
    },
    upload({ raw }) {
      const that = this;
      new Compressor(raw, {
        quality: that.quality / 100,
        success(file) {
          that.loading = true;
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            if (!that.base64) {
              $.ajax({
                type: "POST",
                url: DomainName + "/BusinessPIC",
                data: {
                  Data: e.target.result,
                  DataLength: file.size,
                  FileName: file.name,
                  logo: true,
                },
                complete: function (XMLHttpRequest) {
                  that.loading = false;
                  if (
                    XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT"
                  ) {
                    window.parent.document.location.href =
                      absolutepath() +
                      XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  if (Result.Status == "success") {
                    that.Picture_URL = Result.Picture_Url;
                    that.$message.success("上传成功");
                  } else {
                    that.$message.error("上传失败");
                  }
                },
                error: function () {
                  that.$message.error("操作失败，请稍后再试");
                },
                dataType: "json",
              });
            } else {
              that.Picture_URL = e.target.result;
              that.loading = false;
            }
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    handlePictureCardPreview(formName) {
      this.$refs[formName].showViewer = true;
    },
    handleRemove() {
      this.Picture_URL = "";
      this.$emit("remove");
    },
  },
});
new Vue({
  el: "#app",
  data() {
    const User_Number = (rule, value, callback) => {
      if (!validatemobile(this.form.Mobile)) {
        callback(new Error("请输入有效手机号"));
      } else {
        callback();
      }
    };
    return {
      isPictureChanged: false,

      fileList: [],
      form: {
        Expert_SerialNumber: "",
        Picture_URL: "", //表名
        Expert_Name: "",
        Expert_Type_Name: "",
        ProvinceNumber: "",
        CityNumber: "",
        CountyNumber: "",
        Mobile: "",
        Address: "",
        Notes: "",
        Children: {
          business_expert_type: [
            {
              Expert_Type_SerialNumber: "",
              Expert_SerialNumber: "",
              Category_SerialNumber: "",
            },
          ],
        },
      },
      city: [],
      rules: {
        Category_Name: [
          { required: true, message: "请输入类别名称", trigger: "blur" },
        ],
        Mobile: [{ required: true, validator: User_Number, trigger: "blur" }],
      },
      loading: false,
      category: [],
      type: "",
    };
  },
  mounted() {
    if (getQueryObject().type && getQueryObject().type == "1") {
      this.type = getQueryObject().type;
      $("title").text("确认信息");
      this.getData(getQueryObject().Expert_SerialNumber);
    } else {
      let Expert_SerialNumber = window.sessionStorage.getItem(
        "Expert_SerialNumber"
      );
      this.getData(Expert_SerialNumber);
    }
  },
  methods: {
    handleFileListChange(fileList) {
      this.fileList = fileList;
      if (fileList.length > 0) {
        this.isPictureChanged = true;
      }
    },
    handleChange(file, fileList) {
      // 这个方法现在主要用于调试或处理其他上传后的逻辑
      // 注意：这里的fileList参数与:file-list绑定的fileList不是同一个对象
      // :file-list绑定的fileList是组件内部维护的，而这里的fileList是上传事件提供的
      console.log("Upload change event:", file, fileList);
    },
    handleBeforeUpload(file) {
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        //调用存储的接口放在onload中，存在异步操作
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid, //添加uid
          // 可以添加其他属性，如上传状态等
        };
        this.fileList.push(newFile);
        console.log(this.fileList);

        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.fileList), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // 返回false以阻止自动上传

      return false;
    },
    add_business_expert_type() {
      this.form.Children.business_expert_type.push({
        Expert_Type_SerialNumber: "",
        Expert_SerialNumber: this.form.Expert_SerialNumber,
        Category_SerialNumber: "",
      });
    },
    remove_system_model_mark() {
      if (
        this.form.Children.system_model_mark.filter(
          (item) => item.Row_Status != "1"
        ).length > 0
      ) {
        let i =
          this.form.Children.system_model_mark.filter(
            (item) => item.Row_Status != "1"
          ).length - 1;
        let obj = this.form.Children.system_model_mark.filter(
          (item) => item.Row_Status != "1"
        )[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          this.form.Children.system_model_mark.pop();
        } else {
          this.$confirm(
            "警告！此操作将删除一条权限标识,可能会引起页面问题, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.form.Children.system_model_mark.filter(
                (item) => item.Row_Status != "1"
              )[i].Row_Status = "1";
            })
            .catch(() => {
              this.$message({
                type: "warning",
                message: "已取消删除",
              });
            });
        }
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    remove_business_expert_type() {
      if (
        this.form.Children.business_expert_type.filter(
          (item) => item.Row_Status != "1"
        ).length > 1
      ) {
        let i =
          this.form.Children.business_expert_type.filter(
            (item) => item.Row_Status != "1"
          ).length - 1;
        let obj = this.form.Children.business_expert_type.filter(
          (item) => item.Row_Status != "1"
        )[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          this.form.Children.business_expert_type.pop();
        } else {
          this.form.Children.business_expert_type.filter(
            (item) => item.Row_Status != "1"
          )[i].Row_Status = "1";
        }
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    handle(val) {
      this.form.ProvinceNumber = val[0];
      this.form.CityNumber = val[1];
      this.form.CountyNumber = val[2];
    },
    getData(Primary_Key) {
      const that = this;
      $.ajax({
        url: absolutepath() + "utils/city.json",
        type: "GET",
        success: function (data) {
          that.city = data;
        },
        dataType: "json",
      });
      $.ajax({
        url: `${BASE_URL2}/salesOrder/queryShoppingTrolleyByTableName`,
        type: "GET",
        data: {
          TableName: "business_category",
          Condition: "Row_Status = '0'",
        },
        success: function (res) {
          that.category = res;
        },
        dataType: "json",
      });
      $.ajax({
        url: `${BASE_URL1}/getSubtableInquiryOriginal?grant_type=tourist`,
        type: "POST",
        data: {
          Primary_Key,
          JSONObject: JSON.stringify({
            business_expert: { business_expert_type: {} },
          }),
        },
        success: function ({ business_expert }) {
          console.log({ business_expert });

          if (business_expert.length == 1) {
            that.form = business_expert[0];
            console.log(that.form);

            // return;
            let lArray_URL = new Array();
            let lJSONObject_Picture_Record = new Object();
            lJSONObject_Picture_Record.url = `https://www.kdddy.cn/Image/${that.form.Picture_URL}`;
            lArray_URL.push(lJSONObject_Picture_Record);
            console.log(lArray_URL);

            that.fileList = lArray_URL;

            that.form.value1 = [
              business_expert[0].ProvinceNumber,
              business_expert[0].CityNumber,
              business_expert[0].CountyNumber,
            ];
          }
        },
        dataType: "json",
      });
    },
    handleRemove(file, fileList) {
      this.fileList.splice(0, 1);
    },
    submitForm(formName) {
      console.log(this.fileList);

      // form.Picture_URL = this.fileList[0].

      console.log(this.form);
      console.log(this.type);
      if (this.type == "") {
        if (this.fileList.length > 0 && this.isPictureChanged) {
          let base64Image = this.fileList[0].url;
          let dataIndex = base64Image.indexOf("data:");
          let base64Index = base64Image.indexOf(";base64,");
          let substring = base64Image.substring(dataIndex + 5, base64Index);
          let ls_split = substring.split("/");
          let fileExtension = ls_split[1];
          let newFileName = this.fileList[0].uid + "." + fileExtension;

          // 检查 this.form.Picture_URL 是否已经包含文件扩展名
          if (
            !this.form.Picture_URL ||
            !this.form.Picture_URL.endsWith(`.${fileExtension}`)
          ) {
            this.form.Picture_URL = newFileName;
          }
        }
        //   delete this.form.Children;
        //   let enterpriseInfoWithChildren = JSON.parse(JSON.stringify(this.form)); // 深拷贝 ruleForm
        //   console.log(enterpriseInfoWithChildren);
        let lArray = new Array();
        lArray.push(this.form);
        let lJSONObject_business_expert = new Object();
        lJSONObject_business_expert.business_expert = lArray; //换表
        let lJSONObject_DataSet = new Object(); // Modify
        lJSONObject_DataSet.Modify = lJSONObject_business_expert; //换表
        console.log(lJSONObject_DataSet);
        const _this = this;
        $.ajax({
          headers: {
            AccessToken: $.cookie("token"), //会将数据转换为query string
          },
          url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
          type: "POST",
          data: {
            Data: JSON.stringify(lJSONObject_DataSet),
          },
          success: function (Result) {
            console.log(Result);
            if (Result.Status === "success") {
              _this.$message({
                message: "提交成功",
                type: "success",
              });
              window.history.go(-1);
            } else {
              _this.$message.error("提交失败，请稍后再试");
            }
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
          },
          dataType: "json",
        });
      } else {
        if (this.fileList.length > 0) {
          let url = this.fileList[0].url;
          let newFileName;

          // 判断是否为 base64 格式
          if (url.startsWith("data:")) {
            let base64Image = url;
            let dataIndex = base64Image.indexOf("data:");
            let base64Index = base64Image.indexOf(";base64,");
            let substring = base64Image.substring(dataIndex + 5, base64Index);
            let ls_split = substring.split("/");
            let fileExtension = ls_split[1];
            newFileName = this.fileList[0].uid + "." + fileExtension;
          } else {
            // 不是 base64 格式，直接从 Image/ 后面提取文件名
            let imageIndex = url.indexOf("Image/");
            if (imageIndex !== -1) {
              newFileName = url.substring(imageIndex + "Image/".length);
            } else {
              // 如果没有找到 Image/，则使用默认文件名
              newFileName = this.fileList[0].uid;
            }
          }

          // 检查 this.form.Picture_URL 是否已经包含文件扩展名
          let fileExtension = newFileName.split(".").pop();
          if (
            !this.form.Picture_URL ||
            !this.form.Picture_URL.endsWith(`.${fileExtension}`)
          ) {
            this.form.Picture_URL = newFileName;
          }
        }
        console.log(this.form);
        // console.log(token);
        const _this = this;
        $.ajax({
          headers: {
            AccessToken: $.cookie("token"), //会将数据转换为query string
          },
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          url: "https://service.kdddy.cn/donghuiForRequest/DingDing/AddUser",
          // url: "http://10.1.0.217:8087/DingDing/AddUser",
          type: "POST",
          data: JSON.stringify(this.form), // 使用 JSON.stringify 转换数据
          success: function (Result) {
            console.log(Result);
            if (Result.Status === "success") {
              _this.$message({
                message: "提交成功",
                type: "success",
              });
              window.history.go(-1);
            } else {
              _this.$message.error("提交失败，请稍后再试");
            }
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
          },
          dataType: "json",
        });
      }
    },
    deal() {
      const add = deepClone(this.form);
      const modify = deepClone(this.form);
      let add_business_expert_type = [],
        modify_business_expert_type = [];
      for (const i in modify.Children.business_expert_type) {
        const obj = modify.Children.business_expert_type[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          add_business_expert_type.push(obj);
        } else {
          modify_business_expert_type.push(obj);
        }
      }
      add.Children.business_expert_type = add_business_expert_type;
      modify.Children.business_expert_type = modify_business_expert_type;
      if (
        add_business_expert_type.length == 0 &&
        modify_business_expert_type.length == 0
      ) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
});
